package com.ctgu.redislock02.controller;

import com.ctgu.redislock02.service.ProductsService;
import com.ctgu.redislock02.utils.ApiResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * @ClassName ProductsController
 * @Author Alex2
 * @Date 2025/3/13 16:11
 **/
@RestController
@RequestMapping("/api/products")
public class ProductsController {

    @Autowired
    private ProductsService productsService;

    /**
     * @Author: Alex
     * @Description: 插入商品
     */
    // http://localhost:8080/api/products/insertProduct?id=1&name=knife&stack=100
    @GetMapping("insertProduct")
    public ApiResult insertProduct(@RequestParam("id") Integer id, @RequestParam("name") String name, @RequestParam("stack") Integer stack) {
        return productsService.insertProduct(id, name, stack);
    }

    /**
     * @Author: Alex
     * @Description: SETNX
     */
    // http://localhost:8080/api/products/getProductWithLock?id=1&userId=1
    @GetMapping("getProductWithLock")
    public ApiResult getProductWithLock(@RequestParam("id") Integer id, @RequestParam("userId") Integer userId) {
        return productsService.getProductWithLock(id, userId);
    }

    /**
     * @Author: Alex
     * @Description: SETNX+EX，设置过期时间，避免死锁
     */
    // http://localhost:8080/api/products/getProductWithSetNxEX?id=1&userId=1
    @GetMapping("getProductWithSetNxEX")
    public ApiResult getProductWithSetNxEX(@RequestParam("id") Integer id, @RequestParam("userId") Integer userId) {
        return productsService.getProductWithSetNxEX(id, userId);
    }

    /**
     * @Author: Alex
     * @Description: Lua脚本，保证原子操作
     */
    // http://localhost:8080/api/products/purchaseWithLua?id=1&userId=1
    @GetMapping("purchaseWithLua")
    public ApiResult purchaseWithLua(@RequestParam("id") Integer id, @RequestParam("userId") Integer userId) {
        return productsService.purchaseWithLua(id, userId);
    }

    /**
     * @Author: Alex
     * @Description: Redisson分布式锁库，自动续期，防止死锁
     */
    // http://localhost:8080/api/products/purchaseWithRedisson?id=1&userId=1
    @GetMapping("purchaseWithRedisson")
    public ApiResult purchaseWithRedisson(@RequestParam("id") Integer id, @RequestParam("userId") Integer userId) {
        return productsService.purchaseWithRedisson(id, userId);
    }

    /**
     * @ Author: Alex
     * @ Description: RabbitMQ 流量削峰
     */
    // http://localhost:8080/api/products/purchaseWithRabbitMQ?id=1&userId=1
    @GetMapping("purchaseWithRabbitMQ")
    public ApiResult purchaseWithRabbitMQ(@RequestParam("id") Integer id, @RequestParam("userId") Integer userId) {
        return productsService.purchaseWithRabbitMQ(id, userId);
    }
}